<template>
    <div ref="chartDom" class="chart" :style="chartStyle"></div>
</template>
<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
    colors: {
        type: Array
    },
    list: {
        type: Array,
        default: () => {
            return []
        }
    },
    height: {
        type: Number,
        default: 285
    }
})

const chartDom = ref()
let chart = null

const chartStyle = computed(() => {
    return { height: props.height + 'px' }
})

const options = computed(() => {
    return {
        color: props.colors,
        tooltip: {
            trigger: 'item'
        },
        legend: {
            icon: 'circle',
            orient: 'vertical',
            left: 'right',
            align: 'left',
            formatter: name => {
                const item = props.list.find(item => item.name === name)
                return `${name}：${item.value}`
            }
        },
        series: [
            {
                type: 'pie',
                radius: ['6%', '80%'],
                label: {
                    show: false
                },
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                emphasis: {
                    label: {
                        show: false
                    }
                },
                data: props.list
            }
        ]
    }
})

onMounted(() => {
    chart = echarts.init(chartDom.value)
    refreshChart()
})

const refreshChart = () => {
    chart && chart.setOption(options.value)
}
watch(
    () => props.list,
    () => {
        refreshChart()
    }
)
</script>
